import { createProdMockServer } from "vite-plugin-mock/es/createProdMockServer";
import mockjs from "mockjs";
// console.log(999, mockjs);

// Inspired by jQuery
function createNativeXMLHttpRequest() {
  const isLocal = (function () {
    const rlocalProtocol =
      /^(?:about|app|app-storage|.+-extension|file|res|widget):$/;
    /* eslint-disable no-useless-escape */
    const rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;
    const ajaxLocation = location.href;
    const ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
    return rlocalProtocol.test(ajaxLocParts[1]);
  })();

  return (window as any).ActiveXObject
    ? (!isLocal && createStandardXHR()) || createActiveXHR()
    : createStandardXHR();

  function createStandardXHR() {
    try {
      return new (window as any)._XMLHttpRequest();
    } catch (e) {
      //
    }
  }

  function createActiveXHR() {
    try {
      return new (window as any)._ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      //
    }
  }
}
const xhr = createNativeXMLHttpRequest();
(mockjs as any).XHR.prototype.upload = xhr.upload;
// (window.XMLHttpRequest.prototype as any).upload = xhr.upload;

const modules: Record<string, any> = import.meta.glob("../mock/*.ts", {
  eager: true
});
const mockModules = [];

Object.keys(modules).forEach(key => {
  mockModules.push(...modules[key].default);
});

export function setupProdMockServer() {
  createProdMockServer(mockModules);
}
